﻿using Application.Initialize.Services;
using Application.Share.PrismNames;
using Prism.Events;
using Prism.Modularity;
using Prism.Regions;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using System.Windows.Input;

namespace Application.Initialize.ViewModels
{
    public class InitializeViewModel :ReactiveObject
    {
        private HardwareManager HardwareManager;
        private IModuleManager ModuleManager;
        private IRegionManager RegionManager;
        /// <summary>
        /// 前端显示加载信息
        /// </summary>
        [Reactive]
        public string Message { get; set; } = string.Empty;
        public ICommand InitCommand { get; }
        public ICommand EnterCommand { get; } 


        public InitializeViewModel(
            IEventAggregator eventAggregator,
            IModuleManager moduleManager, 
            IRegionManager regionManager)
        {
            HardwareManager = new(eventAggregator);
            ModuleManager = moduleManager;
            RegionManager = regionManager;
            InitCommand = ReactiveCommand.Create(OnInitAsync);
            EnterCommand = ReactiveCommand.Create(OnEnter);
        }

        private async void OnInitAsync()
        {
            if (!HardwareManager.Initialized)
            {
                Message = "正在初始化硬件...";
                var result = await HardwareManager.InitAsync();
                if (!result.Success)
                {
                    Message = result.Message;
                    return;
                }
            }
            Message = "初始化完成！！";
            OnEnter();
        }

        private async void OnEnter()
        {
            await Task.Delay(100).ContinueWith(t =>
            {
                System.Windows.Application.Current.Dispatcher.Invoke(() =>
                {
                    ModuleManager.LoadModule(ModuleNames.ApplicationMainModule);
                    RegionManager.RequestNavigate(RegionNames.MainRegion, ViewNames.MainView);
                });
            });
        }
    }
}
